<script setup>
import { reactive, ref, watch } from 'vue'
import verify from './verify.vue'
import { useRouter } from 'vue-router';
import { useIndexStore } from '../../pinia';
import { enc, dec } from '../../utils/crypto'
import mitter from '../../utils/mitter';
import { ElMessage } from "element-plus"
import { request } from '@/utils/axios/request.js'
import local from '@/components/local.vue'

let locabob = ref(false)


let checked1 = ref(false)
let imgCode = ref('')
let router = useRouter()
let store = useIndexStore()
let input = reactive({
  'username': '',
  'password': '',
  'code': ''
})
//加密后的密码
let encPass = enc(input.password)
//检查缓存中是否存在
let logins = localStorage.getItem('login')
if (logins) {
  checked1.value = true
  let newlogin = JSON.parse(logins)
  let decPass = dec(newlogin.password[0])
  newlogin.password = decPass
  input = reactive(newlogin)
}


//验证码
let setImg = (data) => {
  imgCode.value = data
}
//登录
const login = async () => {
  if (input.username == '' || input.password == '' || input.code == '') {
    ElMessage.error("信息为空")
    return
  }
  try {
    locabob.value = true
    let times = new Date().toLocaleString()
    let newdata = await request({
      url: `/admin/user/users2?username=${input.username}&password=${input.password}&created_login=${times}`,
      method: 'get'
    })
    if (newdata.code == 200) {
      if (input.code == imgCode.value.toLocaleLowerCase() || input.code == imgCode.value.toLocaleUpperCase() || input.code == imgCode.value) {
        localStorage.setItem('username', input.username)
        localStorage.setItem('token', newdata.token)
        try {
          let newdata1 = await request({
            url: `/admin/user/users1?username=${input.username}`,
            method: 'get'
          })
          //根据权限转动态路由
          store.roleChange(input.username)
          ElMessage.success(newdata.message)
          mitter.emit('namePink', newdata1.data[0].nickname)
          router.push('/index')
        } catch (err) {
          console.log(err);
        }
      } else {
        ElMessage.error("验证码错误")
        input.code = ''
      }

    }
  } catch (err) {
    console.log(err);
    input.username = ''
    input.password = ''
  }
  locabob.value = false
}
let times = new Date().getTime()
let timet = localStorage.getItem('times')
if (timet) {
  if (times >= timet) {
    localStorage.removeItem('login')
    localStorage.removeItem('times')
  }
}

// 记住我
const remember = () => {
  if (checked1.value) {
    let obj = JSON.parse(JSON.stringify(input))
    obj.password = [encPass]
    let newObj = JSON.stringify(obj)
    localStorage.setItem('login', newObj)
    let times = new Date().getTime() + 7 * 24 * 60 * 60 * 1000
    localStorage.setItem('times', times)
  } else {
    localStorage.removeItem('login')
    localStorage.removeItem('times')
  }
}
const jizhu = () => {
  checked1.value = false
  encPass = enc(input.password)
}

//短信验证登录
let disabledShow = ref(false)
let loginShow = ref(true)
let codevalue = ref("发送验证码")
let time = ref(60)
let verifys = ref('')
let codebtn = async () => {
  if (!/^(0\d{2,3}-\d{7,8}(-\d{3,4})?|1[3456789]\d{9})$/.test(tel.value)) {
    ElMessage.error('号码格式错误')
    tel.value = ''
    return;
  }
  try {
    let newdata1 = await request({
      url: `/admin/user/findTel?tel=${tel.value}`,
      method: 'get'
    })
    verifys.value = newdata1.verify
    // console.log(verifys.value);
    time.value = 60
    disabledShow.value = true
    let timer = setInterval(function () {
      time.value--
      if (time.value <= 0) {
        disabledShow.value = false
        clearInterval(timer)
        codevalue.value = "发送验证码"
      }
      else if (time.value > 0) {
        codevalue.value = time.value + "秒后可重发"
        disabledShow.value = true
      }
    }, 1000);
    //根据权限转动态路由
    ElMessage.success(newdata1.message)
  } catch (err) {
    console.log(err);
  }
}


// 验证码
let tel = ref('')
let vefi = ref('')
const tels = async () => {
  if (!/^(0\d{2,3}-\d{7,8}(-\d{3,4})?|1[3456789]\d{9})$/.test(tel.value)) {
    ElMessage.error('号码格式错误')
    tel.value = ''
    return;
  }
  if (codevalue.value == "发送验证码") {
    ElMessage.warning('未发送验证码')
    return;
  }
  if (vefi.value == verifys.value) {
    let times = new Date().toLocaleString()
    let newdata = await request({
      url: `/admin/user/users4?tel=${tel.value}&created_login=${times}`,
      method: 'get'
    })
    localStorage.setItem('username', newdata.data.username)
    localStorage.setItem('token', newdata.token)
    //根据权限转动态路由
    store.roleChange(newdata.data.username)
    ElMessage.success(newdata.message)
    vefi.value = ''
    verifys.value = ''
    tel.value = ''  
    mitter.emit('namePink', newdata.data.nickname)
    router.push('/index')
  } else {
    ElMessage.error('验证码错误')
    vefi.value = ''
  }
}



//用户密码登录
let userlogin = () => {
  loginShow.value = true
}
let tellogin = () => {
  loginShow.value = false
}
</script>

<template>
  <div class="box">
    <local v-show="locabob" />
    <div class="login" v-show="loginShow">
      <div class="tablogin">
        <ul style="display: flex;justify-content: space-evenly; font-size: 18px; margin: 20px 0; cursor: pointer;">
          <li> <span @click="userlogin" :class="{ tabcolor: loginShow }">用户密码登录</span></li>
          <li> <span @click="tellogin" :class="{ tabcolor: !loginShow }">短信验证登录</span> </li>
        </ul>
      </div>
      <el-input class="loginInp loginuser" placeholder="请输入账号" v-model="input.username" @input="jizhu"
        clearable></el-input>
      <el-input class="loginInp loginpass" v-model="input.password" type="password" @input="jizhu" placeholder="密码"
        show-password />
      <div class="yans">
        <el-input class="loginveri" v-model="input.code" placeholder="验证码" />
        <verify @verifyImg='setImg' />
      </div>
      <div>
        <el-checkbox class="remmberme" v-model="checked1" label="记住我？" size="large" @change="remember" />
        <p><el-button type="primary" class="loginbtn" @click="login">登录</el-button></p>
      </div>
    </div>
    <div class="tellogin" v-show="!loginShow">
      <div class="tablogin">
        <ul style="display: flex;justify-content: space-evenly; font-size: 18px; margin: 20px 0;">
          <li> <span @click="userlogin" :class="{ tabcolor: loginShow }">用户密码登录</span></li>
          <li> <span @click="tellogin" :class="{ tabcolor: !loginShow }">短信验证登录</span> </li>
        </ul>
      </div>
      <ul class="tellogin_ul">
        <li>
          <el-input class="loginInp loginuser" placeholder="请输入手机号" v-model="tel" clearable></el-input>
        </li>
        <li>
          <el-input class="loginveri" placeholder="请输入验证码" v-model="vefi" />
          <button type="primary" class="telbtn" @click="codebtn" :disabled="disabledShow">{{ codevalue }}</button>
        </li>
        <li style="margin-top: 20px;">
          <el-button type="primary" class="loginbtn" @click="tels">登录</el-button>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped lang="less">
.tellogin_ul {
  li {
    &:nth-child(2) {
      margin-top: 20px;
    }
  }
}

.tabcolor {
  color: #409eff
}

.box {
  width: 100%;
  height: 100%;
  background-image: url(@/assets/images/login.jpg);
  background-position: center center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1999;

}

.login {
  width: 410px;
  height: 350px;
  background-color: #fff;
  text-align: center;
  position: absolute;
  right: 200px;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 5px;


  .loginInp,
  .loginbtn {
    width: 352px;
    height: 40px;
  }

  .loginuser,
  .loginpass {
    margin-bottom: 20px;
  }

  .remmberme {
    position: relative;
    right: 142px;
  }

  .loginveri {
    width: 192px;
    height: 40px;
  }
}

.tellogin {
  width: 410px;
  height: 350px;
  background-color: #fff;
  text-align: center;
  position: absolute;
  right: 200px;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 5px;


  .loginInp {
    margin-top: 25px;
    width: 352px;
    height: 40px;
  }

  .loginbtn {
    margin-top: 35px;
    width: 352px;
    height: 40px;
  }

  .telbtn {
    width: 110px;
    height: 39px;
    background-color: #fff;
    border: 1px solid #409eff;
    border-radius: 5px;
    margin-left: 10px;
    color: #409eff;
  }

  .loginuser,
  .loginpass {
    margin-bottom: 20px;
  }

  .remmberme {
    position: relative;
    right: 142px;
  }

  .loginveri {
    width: 230px;
    height: 40px;
  }
}

.yans {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 -1px;
}
</style>